package com.smap.control;

import com.google.gwt.canvas.client.Canvas;
import com.google.gwt.canvas.dom.client.Context2d;
import com.smap.common.Utils;
import com.smap.event.MapEvent;

public class StatusControl extends AbstractControl {

	Canvas progressBar;

	Canvas centreCross;

	int max = 0;

	@Override
	void init() {
		progressBar = Canvas.createIfSupported();
		Utils.setCanvasSize(progressBar, 800, 10);
		map.add(progressBar, 0, 0);
		centreCross = Canvas.createIfSupported();
		Utils.setCanvasSize(centreCross, 30, 30);
		map.add(centreCross, (map.getWidth() - 30) / 2,
				(map.getHeight() - 30) / 2);
		Context2d ctx = centreCross.getContext2d();
		int x = 15;
		int y = 15;
		int size = 15;
		ctx.beginPath();
		ctx.moveTo(x - size, y);
		ctx.lineTo(x + size, y);
		ctx.moveTo(x, y + size);
		ctx.lineTo(x, y - size);
		ctx.setStrokeStyle("red");
		ctx.stroke();

		this.activate();
	}

	public void onEvent(MapEvent evt) {
		if (MapEvent.EVT_TILE_FETCHED.equals(evt.type)) {
			Context2d ctx = progressBar.getContext2d();
			int waiting = evt.x;
			int running = evt.y;
			Utils.clearCanvas(progressBar);
			ctx.setGlobalAlpha(0.5);
			if ((waiting + running) > 0) {
				max = Math.max(max, waiting + running);
				double width = map.getWidth();
				double w = width * ((double) (max - running - waiting) / max);
				double w1 = width * ((double) running / max);
				double w2 = width * ((double) waiting / max);
				ctx.setFillStyle("green");
				ctx.fillRect(0, 0, w, 10);
				ctx.setFillStyle("yellow");
				ctx.fillRect(w, 0, w1, 10);
				ctx.setFillStyle("gray");
				ctx.fillRect(w + w1, 0, w2, 10);
			} else {
				max = 0;
			}
			ctx.setGlobalAlpha(1);
		}
	}

	public void onResize() {
		Utils.setCanvasSize(progressBar, map.getWidth(), 4);
		Utils.setPosition(centreCross, (map.getWidth() - 30) / 2,
				(map.getHeight() - 30) / 2);
	}

	public boolean podcast(String cmd) {
		return false;
	}

	@Override
	public void execute(String cmd) {

	}

	@Override
	public String[] getCmd() {
		return null;
	}

}
